
var mongodb 	= require('mongodb'),
	async		= require('async');


var map = function () {
	var x = this.x >> 3,
		y = this.y >> 3;

	if (x > 0 && y > 0) {
		emit(x + "|" + y, {x: x, y: y, count: 1});
	}
}


var reduce = function (key, values) {
	var total = 0;
	for ( var i=0; i<values.length; i++ ) {
		total += values[i].count;
	}
	return {x: values[0].x, y: values[0].y, count: total};
}





var combine = function (m, r, req, res, request, start) {

	if (m instanceof Array && r instanceof Array) {

		var data = {m: m, r: r, page: request.page};

		var duration = new Date().getTime() - start;
		console.log('Processed data with ' + ((m.length/3) + (r.length/4)) + ' coordinates (' + duration + 'ms)');

		if (req && req.query && req.query.cb) {
			res.writeHead(200, {'Content-Type': 'text/javascript'});
			res.end(req.query.cb + "(" + JSON.stringify(data) + ");");
		} else {
			res.writeHead(200, {'Content-Type': 'application/json'});
			res.end(JSON.stringify(data));
		}
	}

}


exports.process = function (req, res, client, request) {

	var collection			= new mongodb.Collection(client, 'clctr_' + request.page.id + '_moves')
	,	start				= new Date().getTime()
	,	data_m				= []
	,	data_r				= []
	,	r					= []
	,	m					= null
	;

	collection.find(function(err, cursor){
		cursor.each(function(err, result) {

			if (result) {
				data_m = data_m || [];

				var id 	= result["_id"]
				  , y	= (id >> 9)
				  , x	= (id & 511); // 2^9-1 = 511

				data_m.push(x, y, result.c);

			} else {
				m = data_m;
				combine(m, r, req, res, request, start);
			}
		});
	});


}
